
package cartagows.wsframework.wssecurity.policy.builders;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.builders.AssertionBuilder;

import cartagows.wsframework.wssecurity.policy.SP11Constants;
import cartagows.wsframework.wssecurity.policy.SPConstants;
import cartagows.wsframework.wssecurity.policy.model.UsernameToken;

public class UsernameTokenBuilder implements AssertionBuilder {

    
    public Assertion build(OMElement element, AssertionBuilderFactory factory) throws IllegalArgumentException {
        UsernameToken usernameToken = new UsernameToken(SPConstants.SP_V11);
        
        OMAttribute attribute = element.getAttribute(SP11Constants.INCLUDE_TOKEN);
        
        if(attribute != null) {
            int inclusion = SP11Constants.getInclusionFromAttributeValue(attribute.getAttributeValue());
            usernameToken.setInclusion(inclusion);
        }
        
        //OMElement policyElement = element.getFirstElement();
        
        //if (policyElement != null && !policyElement.getQName().equals(org.apache.neethi.Constants.Q_ELEM_POLICY)) {
        
            Policy policy = PolicyEngine.getPolicy(element.getFirstElement());
            policy = (Policy) policy.normalize(false);
            
            for (Iterator iterator = policy.getAlternatives(); iterator.hasNext();) {
                processAlternative((List) iterator.next(), usernameToken);
                
                /*
                 * since there should be only one alternative
                 */
                break;
            }            
        //}
        
        return usernameToken;
    }
        
    public QName[] getKnownElements() {
        return new QName[] {SP11Constants.USERNAME_TOKEN};
    }

    private void processAlternative(List assertions, UsernameToken parent) {
                
        for (Iterator iterator = assertions.iterator(); iterator.hasNext();) {
            Assertion assertion = (Assertion) iterator.next();
            QName qname = assertion.getName();
            
            if (SP11Constants.WSS_USERNAME_TOKEN10.equals(qname)) {
                parent.setUseUTProfile10(true);
                
            } else if (SP11Constants.WSS_USERNAME_TOKEN11.equals(qname)) {
                parent.setUseUTProfile11(true);
            
            } else if (SPConstants.HASH_PASSWORD.equals(qname.getLocalPart())) {
                parent.setHashPassword(true);
            
            } else if (SPConstants.NO_PASSWORD.equals(qname.getLocalPart())) {
                parent.setNoPassword(true);
            }
        }
    }
}
